package com.jzqf.harmonydemo.utils.image;

import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Rect;
import ohos.media.image.common.Size;

import java.io.File;

/**
 * 图片工具类
 *
 * @author LiuWeiHao
 * 2021/5/22 17:57
 */
public class ImageUtil {
    /**
     * 图片本地路径转图片
     *
     * @param path 图片本地绝对路径
     * @return 图片
     */
    public static PixelMap path2PixelMap(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return null;
        }
        ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
//        ImageSource imageSource = ImageSource.create(file, srcOpts);
        ImageSource imageSource = ImageSource.create(path, srcOpts);
        if (imageSource == null) {
            return null;
        }
        ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
        decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
        decodingOptions.desiredSize = new Size(0, 0);//按尺寸缩放,0为不缩放
        //按矩形区域剪裁,0为不剪裁
        decodingOptions.desiredRegion = new Rect(0, 0, 0, 0);
        decodingOptions.rotateDegrees = 90f;//顺时针旋转0-360f
        return imageSource.createPixelmap(decodingOptions);
    }

    /**
     * 字节数组转图片
     *
     * @param bytes 字节数组
     * @return 图片
     */
    public static PixelMap bytes2PixelMap(byte[] bytes) {
        ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
        ImageSource imageSource = ImageSource.create(bytes, srcOpts);
        if (imageSource == null) {
            return null;
        }
        //普通解码
        return imageSource.createPixelmap(null);
    }
}
